//
//  Shader.fsh
//  Renderbunny
//
//  Created by Holmes Futrell on 1/20/11.
//  Copyright 2011 Holmes Futrell. All rights reserved.
//

uniform sampler2D depthSampler;
uniform sampler2D normalSampler;
uniform sampler2D ambientSampler;

uniform int filterSize;
uniform float variance;

uniform vec2 invImageSize;

varying vec2 uv;

const float epsilon = 0.0001;

void main()
{

	vec3 normal = normalize(2.0 * texture2D(normalSampler, uv).rgb - 1.0);
	float depth = texture2D(depthSampler, uv).r;

	vec3 accum_color = vec3(0.0, 0.0, 0.0);
	float accum_weights = 0.0;
	
	for (int i=-filterSize; i<=filterSize; i++) {
		for (int j=-filterSize; j<=filterSize; j++) {

			float ii = float(i);
			float jj = float(j);

			vec2 sampleUV = uv + invImageSize * vec2(ii, jj);
			
			vec3 sampleNormal = normalize(2.0 * texture2D(normalSampler, sampleUV).rgb - 1.0);

			float sampleDepth = texture2D(depthSampler, sampleUV).r; 

			float weight = exp(-(ii*ii+jj*jj) / ( 2.0 * variance ));
			
			if ( sampleDepth - epsilon > depth ) {
				weight = 0.0;
			}
			
			weight *= max( dot(normal, sampleNormal), 0.0);
			
			vec3 sample = texture2D(ambientSampler, sampleUV).rgb;
			
			accum_color	  += sample * weight;
			accum_weights += weight;

		}
	}

	accum_color /= accum_weights;

	gl_FragColor = vec4(accum_color, 1.0);
	
}